package com.supermap;

import java.io.*;
import java.util.logging.Logger;

/**
 * @author liqs
 * @version 1.0
 * @date 2021/10/14 16:54
 */
public class Utils {

    private static Logger logger = Logger.getLogger(Utils.class.toString());

    /**
     * 向文件写入byte[]
     *
     * @param fileName 文件名
     * @param bytes    字节内容
     * @param append   是否追加
     * @throws IOException
     */
    public static void writeBytesToFile(String fileName, byte[] bytes, boolean append) throws IOException {
        try{
            OutputStream out = new BufferedOutputStream(new FileOutputStream(fileName, append));
            out.write(bytes);
        } catch (Exception e) {
            logger.info(e.getMessage());
        }
    }

    public static void writeBytesToFile(String fileName, byte[] bytes) throws IOException {
        try{
            OutputStream out = new BufferedOutputStream(new FileOutputStream(fileName, false));
            out.write(bytes);
        } catch (Exception e) {
            logger.info(e.getMessage());
        }
    }


    /**
     * the traditional io way
     *
     * @param filename
     * @return
     * @throws IOException
     */
    public static byte[] readFiletoBytes(String filename) throws IOException {

        File f = new File(filename);
        if (!f.exists()) {
            throw new FileNotFoundException(filename);
        }

        ByteArrayOutputStream bos = new ByteArrayOutputStream((int) f.length());
        BufferedInputStream in = null;
        try {
            in = new BufferedInputStream(new FileInputStream(f));
            int buf_size = 1024;
            byte[] buffer = new byte[buf_size];
            int len = 0;
            while (-1 != (len = in.read(buffer, 0, buf_size))) {
                bos.write(buffer, 0, len);
            }
            return bos.toByteArray();
        } catch (IOException e) {
            e.printStackTrace();
            throw e;
        } finally {
            try {
                in.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            bos.close();
        }
    }

}
